package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.AsyncDimFunction_lj;
import com.atguigu.bean.PageBean;
import com.atguigu.util.ClickHouseUtil_lj;
import com.atguigu.util.DateFormatUtil_hjy;
import com.atguigu.util.DateFormatUtil_lj;
import com.atguigu.util.MyKafkaUtil_lj;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import scala.math.BigInt;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.HashSet;

/**
 * @Author 晶晶          1.5.1 各试卷考试统计   已跑通
 * @Date 2023 03 25 14 43
 **/
public class Dws_ExamInfo {
    public static void main(String[] args) throws Exception {
        //获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //从Kafka中读取数据
        String topic = "dwd_test_exam";
        String groupId = "dws_exam_Info00";
        DataStreamSource<String> dataStream = env.addSource(MyKafkaUtil_lj.getFinkKafkaConsumer(topic, groupId));

        //dataStream.print(">>>>>>>>>>>>>>>>>>>");

        //转为Jason格式
        SingleOutputStreamOperator<JSONObject> jsonDs = dataStream.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSON.parseObject(value));
                }
            }
        });

        //提取时间戳 获取watermark
        SingleOutputStreamOperator<JSONObject> dsWithWM = jsonDs.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("create_time");
                    }
                }));

        //根据id分组 keyby
        KeyedStream<JSONObject, String> keyedByIdDs = dsWithWM.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getString("paper_id");
            }
        });

        //转为javabean
        SingleOutputStreamOperator<PageBean> beanDs = keyedByIdDs.flatMap(new RichFlatMapFunction<JSONObject, PageBean>() {

//            private ValueState<String> lastExamState;
//
//            @Override
//            public void open(Configuration parameters) throws Exception {
//                StateTtlConfig stateTTL = StateTtlConfig.newBuilder(org.apache.flink.api.common.time.Time.days(1))
//                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite).build();
//
//                ValueStateDescriptor<String> stateProperties = new ValueStateDescriptor<>("lastExam-state", String.class);
//                stateProperties.enableTimeToLive(stateTTL);
//                lastExamState = getRuntimeContext().getState(stateProperties);
//            }

            @Override
            public void flatMap(JSONObject value, Collector<PageBean> out) throws Exception {

                    HashSet<String> ids = new HashSet<>();
                    ids.add(value.getString("user_id"));
                    out.collect(PageBean.builder()
                            .page_id(value.getString("paper_id"))
                            .userIds(ids)
                            .sumScore(value.getInteger("score"))
                            .durations(value.getLong("duration_sec"))
                            .build());
                }

        });


        //开窗聚合
        SingleOutputStreamOperator<PageBean> resultDs = beanDs.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<PageBean>() {
                            @Override
                            public PageBean reduce(PageBean value1, PageBean value2) throws Exception {
                                value1.setSumScore(value1.getSumScore() + value2.getSumScore());
                                value1.setDurations(value1.getDurations() + value2.getDurations());
                                value1.getUserIds().addAll(value2.getUserIds());
                                return value1;
                            }
                        },
                        new AllWindowFunction<PageBean, PageBean, TimeWindow>() {

                            @Override
                            public void apply(TimeWindow window, Iterable<PageBean> values, Collector<PageBean> out) throws Exception {
                                for (PageBean next : values) {
                                    next.setStt(DateFormatUtil_lj.toYmdHms(window.getStart()));
                                    next.setEdt(DateFormatUtil_lj.toYmdHms(window.getEnd()));
                                    next.setTs(System.currentTimeMillis());

                                    next.setUserCn((long) next.getUserIds().size());
                                    next.setAvgScore((double) (next.getSumScore() / next.getUserIds().size()));
                                    next.setAvgDuration((double) (next.getDurations() / next.getUserIds().size()));
                                    out.collect(next);
                                }


                            }
                        });

        //写入clickhouse
        resultDs.print(">>>>>>>>>>>>>>>>>>");
        resultDs.addSink(ClickHouseUtil_lj.getClickHouseSink("insert into dws_study_exam_info values(?,?,?,?,?,?,?)"));

        //运行任务
        env.execute();
    }
}
